package org.yaac.server.egql.evaluator.aggregator;

import java.math.BigDecimal;
import java.util.Date;

import org.yaac.server.egql.evaluator.EvaluationResult;

/**
 * @author Max Zhu (thebbsky@gmail.com)
 *
 */
public class MinAggregator implements Aggregator {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private BigDecimal min;
	
	/**
	 * 
	 */
	public MinAggregator() {
		min = null;
	}
	
	@Override
	public void aggregate(EvaluationResult delta) {
		if (delta.getPayload() == null) {
			// do nothing
			return;
		}
		
		if (delta.getPayload() instanceof Boolean) {
			Boolean val = (Boolean) delta.getPayload();
			if (val) {
				min = min(min, BigDecimal.ONE);
			} else {
				min = min(min, BigDecimal.ZERO);
			}
		} else if (delta.getPayload() instanceof BigDecimal) {
			min = min(min, (BigDecimal) delta.getPayload());
		} else if (delta.getPayload() instanceof Date) {
			Date d = (Date) delta.getPayload();
			min = min(min, new BigDecimal(d.getTime()));
		}
	}

	@Override
	public String asString() {
		return min == null ? "" : min.toPlainString();
	}

	private BigDecimal min(BigDecimal bd1, BigDecimal bd2) {
		return (bd1 == null) ? bd2 :
			bd1.compareTo(bd2) < 0 ? bd1 : bd2;
	}

	@Override
	public BigDecimal getResult() {
		return min;
	}
}
